//
//  GAOOAuthController.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

//  新浪微博的appkey
let client_id = "4243212054"
//  授权回调页
let redirect_uri = "http://git.oschina.net/gaochen"
//  AppSecret
let AppSecret = "715bc42e528a065119096fa482829cd9"
class GAOOAuthController: UIViewController {
    
    
    //https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
    
    //懒加载WebView
    private lazy var webView : UIWebView = UIWebView()
    //自定义View
    override func loadView() {
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavUI()
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)")
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        // Do any additional setup after loading the view.
    }

    
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelButtonAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 15, target: self, action: "autoFillButtonAction")
        navigationItem.title = "微博登陆"
    }
    
    
    @objc private func cancelButtonAction() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillButtonAction() {
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin012'")
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


//  MARK: UIWebViewDelegate

extension GAOOAuthController:UIWebViewDelegate {

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果地址为nil就不执行加载
        guard let url = request.URL else {
            
            return false
        }
        
        if !url.absoluteString.hasPrefix(redirect_uri) {
        //  取反表示此处不许关注的url,直接加载
            return true
        }
        
        //  代码执行到此,就是我们关注的这个url
        //  截取授权码code
        if let query = url.query where query.hasPrefix("code=") {
            let code = query.substringFromIndex("code=".endIndex)
            GAOUserAccountViewModel.UserAccountViewModel.requsetAccesstoken(code, complete: { (isSuccess) -> () in
                if isSuccess {
                    print("登陆成功")
                    self.dismissViewControllerAnimated(true, completion: {[weak self] () -> Void in
                        // 进入欢迎页面
                        NSNotificationCenter.defaultCenter().postNotificationName(SwichRootVCNotification, object: self)
                    })
                    
                    
                }else {
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
            })
        }else {
            //  取消授权
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        
        
        return false
    }
    
    //开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载请求完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }

}

